<template>
  <div>
    <el-form class="projectForm" ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
      <el-tabs v-model="activeName" @tab-click="TabClick" style="width:100%">
        <el-tab-pane label="基本内容" name="first">
          <el-form-item label="项目名称" prop="fName">
            <el-input v-model="formData.fName" placeholder="请输入项目名称" clearable :style="{width: '100%'}"
                      :readonly="showAdd.readonly"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="项目编号" prop="fNumber">
            <el-input v-model="formData.fNumber" placeholder="请输入项目编号" clearable :style="{width: '100%'}"
                      :readonly="shoCbProStatisticTablewAdd.readonly"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="产业类型" prop="fType">
            <el-input v-model="formData.fType" placeholder="请输入产业类型（种植品种）" clearable :style="{width: '100%'}"
                      :readonly="showAdd.readonly"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="建设地点" prop="fAddress">
            <el-input v-model="formData.fXzqmc" class="xjxzq-input" :readonly="true"></el-input>
            <el-input v-model="formData.fAddress" placeholder="请输入详细建设地点(乡、镇、村等)" clearable
                      style="width: 100%;margin-top: 10px;" :readonly="showAdd.readonly"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="建设内容" prop="fContent">
            <el-input class="addressDetail" v-model="formData.fContent" type="textarea" placeholder="请输入建设内容"
                      :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}" :readonly="showAdd.readonly"
            ></el-input>
          </el-form-item>
          <el-form-item label="建设规模（万亩）" prop="fScaleArea">
            <el-input v-model="formData.fScaleArea" placeholder="请输入建设规模（万亩）" clearable :style="{width: '100%'}"
                      oninput="value=value.replace(/[^0-9.]/g,'')" :readonly="showAdd.readonly"
            >
            </el-input>
          </el-form-item>
          <el-form-item size="large">
            <el-col>
              <el-button type="primary" circle @click="Next(2)" icon="el-icon-right"></el-button>
            </el-col>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="详细信息" name="second">
          <el-row type="flex" justify="start" align="top">
            <el-col :span="8">
              <el-form-item label="喷灌(万亩)" prop="fIrrigatePen">
                <el-input v-model="formData.fIrrigatePen" placeholder="喷灌" clearable :style="{width: '100%'}"
                          oninput="value=value.replace(/[^0-9.]/g,'')" :readonly="showAdd.readonly"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="微灌(万亩)" prop="fIrrigateWei">
                <el-input v-model="formData.fIrrigateWei" placeholder="微灌" clearable :style="{width: '100%'}"
                          oninput="value=value.replace(/[^0-9.]/g,'')" :readonly="showAdd.readonly"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="管灌(万亩)" prop="fIrrigateGuan">
                <el-input v-model="formData.fIrrigateGuan" placeholder="管灌" clearable :style="{width: '100%'}"
                          oninput="value=value.replace(/[^0-9.]/g,'')" :readonly="showAdd.readonly"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="申报总投资" prop="fPlanTotal">
                <el-input v-model="formData.fPlanTotal" placeholder="请输入申报总投资" clearable
                          oninput="value=value.replace(/[^0-9.]/g,'')"
                          :style="{width: '100%'}" :readonly="showAdd.readonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="中央资金" prop="fPlanCentral">
                <el-input v-model="formData.fPlanCentral" placeholder="请输入中央资金" clearable
                          oninput="value=value.replace(/[^0-9.]/g,'')"
                          :style="{width: '100%'}" :readonly="showAdd.readonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="市县配套资金" prop="fPlanShixian">
                <el-input v-model="formData.fPlanShixian" placeholder="请输入市县配套资金" clearable
                          oninput="value=value.replace(/[^0-9.]/g,'')"
                          :style="{width: '100%'}" :readonly="showAdd.readonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="自筹资金" prop="fPlanSelf">
                <el-input v-model="formData.fPlanSelf" placeholder="请输入自筹资金" clearable
                          oninput="value=value.replace(/[^0-9.]/g,'')"
                          :style="{width: '100%'}" :readonly="showAdd.readonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="fPlanSelf">
                <el-input class="addressDetail" v-model="formData.fDesc" type="textarea" placeholder="请输入备注信息"
                          :autosize="{minRows: 2, maxRows: 4}" :style="{width: '100%'}" :readonly="showAdd.readonly"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="项目范围">
              <el-button type="primary"  @click="openLoadshpPanel" style="float: left">上传shp</el-button>
              <Loadshp :map="map" :mcShow="mcShow" v-if="mcShow.uploadshp==='loadshp'" :handleLoadFeatoMap="handleLoadFeatoMap"
                      ></Loadshp>
            </el-form-item>
          </el-row>
          <el-form-item size="large">
            <el-col :span="12">
              <el-button type="primary" circle @click="Next(1)" icon="el-icon-back"></el-button>
            </el-col>
            <el-col :span="12">
              <el-button type="primary" circle @click="Next(3)" icon="el-icon-right"></el-button>
            </el-col>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="与历年高标准项目叠被" name="third">
          <div >
            <el-form-item size="large">
              <el-row>
                <el-button type="primary" @click="ZoomToExtent" size="medium">项目范围</el-button>
                <el-button type="primary" value="historyproject" @click="StartAnalysis" size="medium"
                           :disabled="analyDisabled">开始分析</el-button>
              </el-row>
              <el-row class="cbstform">
                <div class="emptyinfo" v-if="mcShow.showEmptyResult.historyproject">
                  分析结果为空<br/>当前项目不与{{ divType.historyproject.cn }}重叠
                </div>
                <AttributeTable  v-if="mcShow.attributeShow.historyproject" :tableconfig="attributeTable2" :overSource="overSource"
                ></AttributeTable>
                <AnalysisStatistic :attributeTable="attributeTable" :divType="divType.historyproject.name"
                                   :overSource="overSource" v-if="mcShow.showStatics.historyproject"
                ></AnalysisStatistic>
              </el-row>
              <el-row v-if="formData.fId != null" class="cbstform">
                <div class="seeinfo">提供的分析结果如下所示</div>
                <div class="seeinfo" v-if="anaATFeasConfig.historyproject.length===0">分析结果为空，表明该项目与{{ divType.historyproject.cn }}不相交</div>
                <AttributeTable v-if="anaATFeasConfig.historyproject.length===5" :overSource="overSource"
                                :tableconfig="anaATFeasConfig.historyproject"
                ></AttributeTable>
                <CbProStatisticTable v-if="anaATFeasConfig.historyproject.length===5" :staticsTable="JSON.parse(formData_Ori.fHistorygbzTable)"
                                     :infoflag="divType.historyproject.cn"
                ></CbProStatisticTable>
              </el-row>

            </el-form-item>
            <el-form-item size="large" class="next-last">
              <el-row>
                <el-col :span="12">
                  <el-button type="primary" circle @click="Next(2)" icon="el-icon-back"></el-button>
                </el-col>
                <el-col :span="12">
                  <el-button type="primary" circle @click="Next(4)" icon="el-icon-right"></el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </div>
        </el-tab-pane>
        <el-tab-pane label="与生态红线叠被" name="fourth">
          <el-form-item size="large">
            <el-row>
              <el-button type="primary" @click="ZoomToExtent" size="medium">项目范围</el-button>
              <el-button type="primary" value="redline" @click="StartAnalysis" size="medium" :disabled="analyDisabled">
                开始分析
              </el-button>
            </el-row>
            <el-row class="cbstform">
              <div class="emptyinfo" v-if="mcShow.showEmptyResult.redline">分析结果为空<br/>当前项目不与{{ divType.redline.cn }}重叠
              </div>
              <AttributeTable v-if="mcShow.attributeShow.redline" :tableconfig="attributeTable2" :overSource="overSource"
              ></AttributeTable>
              <AnalysisStatistic :attributeTable="attributeTable" :divType="divType.redline.name"
                                 :overSource="overSource" v-if="mcShow.showStatics.redline"
              ></AnalysisStatistic>
            </el-row>
            <el-row v-if="formData.fId != null" class="cbstform">
              <div class="seeinfo">提供的分析结果如下所示</div>
              <div class="seeinfo" v-if="anaATFeasConfig.redline.length===0">分析结果为空，表明该项目与{{ divType.redline.cn }}不相交</div>
              <AttributeTable v-if="anaATFeasConfig.redline.length===5"
                              :tableconfig="anaATFeasConfig.redline" :overSource="overSource"
              ></AttributeTable>
              <CbProStatisticTable  v-if="anaATFeasConfig.redline.length===5" :staticsTable="JSON.parse(formData_Ori.fRedlineTable)"
                                   :infoflag="divType.redline.cn"
              ></CbProStatisticTable>
            </el-row>
          </el-form-item>
          <el-form-item size="large" class="next-last">
            <el-row>
              <el-col :span="12">
                <el-button type="primary" circle @click="Next(3)" icon="el-icon-back"></el-button>
              </el-col>
              <el-col :span="12">
                <el-button type="primary" circle @click="Next(5)" icon="el-icon-right"></el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="与自然保护地叠被" name="fifth">
          <el-form-item size="large">
            <el-row>
              <el-button type="primary" @click="ZoomToExtent" size="medium">项目范围</el-button>
              <el-button type="primary" value="naturalreserve" @click="StartAnalysis" size="medium"
                         :disabled="analyDisabled"
              >开始分析
              </el-button>
            </el-row>
            <el-row class="cbstform">
              <div class="emptyinfo" v-if="mcShow.showEmptyResult.naturalreserve">
                分析结果为空<br/>当前项目不与{{ divType.naturalreserve.cn }}重叠
              </div>
              <AttributeTable v-if="mcShow.attributeShow.naturalreserve" :tableconfig="attributeTable2" :overSource="overSource"
              ></AttributeTable>
              <AnalysisStatistic :attributeTable="attributeTable" :divType="divType.naturalreserve.name"
                                 :overSource="overSource" v-if="mcShow.showStatics.naturalreserve"
              ></AnalysisStatistic>
            </el-row>
            <el-row v-if="formData.fId != null" class="cbstform">
              <div class="seeinfo">提供的分析结果如下所示</div>
              <div class="seeinfo" v-if="anaATFeasConfig.naturalreserve.length===0">分析结果为空，表明该项目与{{ divType.naturalreserve.cn }}不相交</div>
              <AttributeTable v-if="anaATFeasConfig.naturalreserve.length===5" :overSource="overSource"
                              :tableconfig="anaATFeasConfig.naturalreserve"
              ></AttributeTable>
              <CbProStatisticTable v-if="anaATFeasConfig.naturalreserve.length===5" :staticsTable="JSON.parse(formData_Ori.fNaturalreserveTable)"
                                   :infoflag="divType.naturalreserve.cn"
              ></CbProStatisticTable>
            </el-row>
          </el-form-item>
          <el-form-item size="large" class="next-last">
            <el-row>
              <el-col :span="12">
                <el-button type="primary" circle @click="Next(4)" icon="el-icon-back"></el-button>
              </el-col>
              <el-col :span="12">
                <el-button type="primary" circle @click="Next(6)" icon="el-icon-right"></el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="与水源保护地叠被" name="sixth">
          <el-form-item size="large">
            <el-row>
              <el-button type="primary" @click="ZoomToExtent" size="medium">项目范围</el-button>
              <el-button type="primary" value="waterprotect" @click="StartAnalysis" size="medium"
                         :disabled="analyDisabled"
              >开始分析
              </el-button>
            </el-row>
            <el-row class="cbstform">
              <div class="emptyinfo" v-if="mcShow.showEmptyResult.waterprotect">
                分析结果为空<br/>当前项目不与{{ divType.waterprotect.cn }}重叠
              </div>
              <AttributeTable v-if="mcShow.attributeShow.waterprotect" :tableconfig="attributeTable2" :overSource="overSource"></AttributeTable>
              <AnalysisStatistic :attributeTable="attributeTable" :divType="divType.waterprotect.name"
                                 :overSource="overSource" v-if="mcShow.showStatics.waterprotect"
              ></AnalysisStatistic>
            </el-row>
            <el-row v-if="formData.fId != null" class="cbstform">
              <div class="seeinfo">提供的分析结果如下</div>
              <div class="seeinfo" v-if="anaATFeasConfig.waterprotect.length===0">分析结果为空，表明该项目与{{ divType.waterprotect.cn }}不相交</div>
              <AttributeTable v-if="anaATFeasConfig.waterprotect.length===5" :overSource="overSource"
                              :tableconfig="anaATFeasConfig.waterprotect"
              ></AttributeTable>
              <CbProStatisticTable v-if="anaATFeasConfig.waterprotect.length===5" :staticsTable="JSON.parse(formData_Ori.fWaterprotecTable)"
                                   :infoflag="divType.waterprotect.cn"
              ></CbProStatisticTable>
            </el-row>
          </el-form-item>
          <el-form-item size="large" class="next-last">
            <el-row>
            <el-col :span="12">
              <el-button type="primary" circle @click="Next(5)" icon="el-icon-back"></el-button>
            </el-col>
            <el-col :span="12">
              <!--              <el-button type="primary" circle @click="Next(7)" icon="el-icon-right"></el-button>-->
              <el-button type="danger" class="savebtn" @click="submitForm" v-if="showAdd.readonly===false">保存
              </el-button>
            </el-col>
              </el-row>
          </el-form-item>

        </el-tab-pane>
        <el-tab-pane label="与国土空间规划叠被" name="seventh" v-if="false">
          <el-form-item size="large">
            <el-row>
              <el-button type="primary" @click="ZoomToExtent" size="medium">项目范围</el-button>
              <el-button type="primary" value="landspace" @click="StartAnalysis" size="medium"
                         :disabled="analyDisabled"
              >开始分析
              </el-button>
            </el-row>
            <el-row class="cbstform">
              <div class="emptyinfo" v-if="mcShow.showEmptyResult.landspace">分析结果为空<br/>当前项目不与{{
                  divType.landspace.cn
                }}重叠
              </div>
              <AnalysisStatistic :attributeTable="attributeTable" :divType="divType.landspace.name"
                                 :overSource="overSource" v-if="mcShow.showStatics.landspace"
              ></AnalysisStatistic>
            </el-row>
            <el-row v-if="formData.fId != null" class="cbstform">
              <div class="seeinfo">提供的分析结果如下</div>
              <div class="seeinfo" v-if="anaATFeasConfig.landspace.length===0">分析结果为空，表明该项目与{{ divType.landspace.cn }}不相交</div>
              <AttributeTable v-if="anaATFeasConfig.landspace.length===5" :overSource="overSource"
                              :tableconfig="anaATFeasConfig.landspace"
              ></AttributeTable>
              <CbProStatisticTable class="cbsform" v-if="anaATFeasConfig.landspace.length===5" :staticsTable="JSON.parse(formData_Ori.fLandspaceTable)"
                                   :infoflag="divType.landspace.cn"
              ></CbProStatisticTable>
            </el-row>
          </el-form-item>
          <el-form-item size="large">
            <el-button type="primary" circle @click="Next(6)" icon="el-icon-back"></el-button>

            <!--            <el-button type="danger" class="savebtn" @click="submitForm" v-if="showAdd.readonly===false">保存</el-button>-->

          </el-form-item>

        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div >
    <div id="proMap" class="right-panel">
      <div id="mouse-position" class="mouse-position"></div><!--鼠标坐标信息-->
      <MapSource ref="bottomMapSource" class="layer-switch" :map="map" v-if="mapSourceLoad===true"></MapSource>
      <!--      <DrawPlotting ref="drawPlotting" v-if="mcShow.drawPlotting==='drawPlotting'"-->
      <!--                    :plotConfig="{map:map,overSource:overSource,mcShow:mcShow}"></DrawPlotting>-->
      <div class="catalog-div">
        <Catalog :map="map"  :projectShowDatas="config.projectLayerTreeData" :layerVisable="layerVisable"></Catalog>
      </div>
    </div>
    <ViewVerify v-show="formData.todotype === 'todo'"
                :row="formData"
                :taskDefKey="formData.taskDefKey?formData.taskDefKey.toString():'0'"
                :taskId="formData.taskId?formData.taskId.toString():'0'"
                :taskName="formData.taskName?formData.taskName.toString():'0'"
                :type="formData.todotype"
                :showAdd="showAdd"
               class="ri-bot"
    >
    </ViewVerify>
    </div>
    <!--    <div ref="closeCP" class="closeCP" @click="closeThisCom">关闭</div>-->
    <el-button
      type="danger"
      size="mini"
      class="closeCP"
      @click="closeThisCom"
    >关闭
    </el-button>

    <!--    <el-button type="primary" class="closeCP"  v-print="printObj">打印</el-button>-->
    <div ref="mapBtns" class="map-btns">
      <div class="map-btn" title="定位" v-show="mcShow.loPosition">
        <i class="wyicon-dingwei1" type="localPosition" title="定位" @click="ChangeMenuCss"></i><label>定位</label>
        <div v-show="showBtn.rightbtns==='localPosition'" class="localPosition-popup">
          <div><span class="coordinateX">x：</span><span type="lon"><input type="text"
                                                                          ref="lp_coordinateX_text"
          /></span></div>
          <div><span class="coordinateY">y：</span><span type="lat"><input type="text"
                                                                          ref="lp_coordinateY_text"
          /></span></div>
          <span type="position" title="定位" @click="localPositionClickSpan">定位</span>
          <span type="position" title="取消" @click="localPositionCloseSpan">取消</span>
        </div>
      </div>
      <div class="map-btn" type="measure" title="测量"
           v-show="setVisible([showBtn.measureLength,showBtn.measureArea,showBtn.drawPlotting])"
           @click="ChangeMenuCss"
      >
        <i class="title-btn wyicon-icon_measureTool"></i>
        <div class="sub-menu" v-show="showBtn.rightbtns==='measure'">
          <div class="map-btn " type="measureLength" title="量距" v-show="showBtn.measureLength"
               @click="mapBtnIClick"
          >
            <i class="wyicon-celiang"></i><label>量距</label>
          </div>
          <div class="map-btn " type="measureArea" title="量面积" v-show="showBtn.measureArea"
               @click="mapBtnIClick"
          >
            <i class="wyicon-map-area"></i><label>面积</label>
          </div>
          <div class="map-btn" type="drawPlotting" title="标绘" v-show="showBtn.drawPlotting"
               @click="mapBtnIClick"
          >
            <i class="wyicon-shuqian"></i><label>标绘</label>
          </div>
        </div>
        <label>测量</label>
      </div>
      <div class="map-btn" type="clearSelected" title="清除" v-show="showBtn.clearSelected"
           @click="mapBtnIClick($event),ChangeMenuCss($event)"
      >
        <i class="wyicon-clean"></i><label>清除</label>
      </div>
    </div>
  </div>
</template>
<script>
import MapSource from '@/components/Map/MapSource'
import DrawPlotting from '@/components/Map/DrawPlotting'
import globalmf from '@/utils/Global/GlobalMapFunction'
import Catalog from '@/views/business/gbzcb/Catalog'
import AnalysisStatistic from '@/views/business/gbzcb/AnalysisStatistic'
import AttributeTable from '@/views/business/gbzcb/AttributeTable'
// import gConfig from '@/utils/GlobalConfig'
import axios from 'axios'
import Bus from '@/utils/bus'
import { addGbzcb, updateGbzcb } from '@/api/business/gbzcb'
import {getxzqGeom} from '@/api/gbznt/gbzCommon'
import request from '@/utils/request'
import XzqList from '@/components/Xzq/XzqList'
import CbProStatisticTable from '@/views/business/gbzcb/CbProStatisticTable'
import ViewVerify from '@/components/Activiti/ViewVerify/ViewVerify'
import printtest from '@/views/business/gbzcb/printtest'
import { Loading } from 'element-ui'
import {getCatalogQueryConfigListByIds, getXzqServerConfigList} from "@/api/portal/catalog";
import {uploadShpFileZip} from "@/api/portal/ioGisFile";
import Loadshp from '@/components/Map/Loadshp'

export default {
  components: {
    Loadshp,
    CbProStatisticTable,
    XzqList,
    MapSource,
    DrawPlotting,
    Catalog,
    AnalysisStatistic,
    ViewVerify,
    printtest,
    AttributeTable
  },
  props: {
    showAdd: {
      type: Object,
      default() {
        return {}
      }
    },
    taskId: {
      type: String
    },
    taskName: {
      type: String
    },
    type: {
      type: String,
      default: 'none'
    },
    formData: {
      type: Object,
      default() {
        return {}
      }
    },

  },
  data() {
    return {
      printObj: {
        id: 'proPrintTest',//id
        popTitle: '我是标题'//自定义设置标题
      },
      loadingtext: '',
      mapSourceLoad:false,//mapSource加载
      layerVisable: false,//高标准农田的所有专题数据不能显示，因为运行在外网。
      divType: {
        redline: { name: 'redline', ftable: 'fRedlineTable', ffeas: 'fRedlineFeas', cn: '生态红线' },
        historyproject: { name: 'historyproject', ftable: 'fHistorygbzTable', ffeas: 'fHistorygbzFeas', cn: '历史高标准项目' },
        naturalreserve: {
          name: 'naturalreserve',
          ftable: 'fNaturalreserveTable',
          ffeas: 'fNaturalreserveFeas',
          cn: '自然保护区'
        },
        waterprotect: { name: 'waterprotect', ftable: 'fWaterprotecTable', ffeas: 'fWaterprotectFeas', cn: '饮用水水源保护地' }
        // landspace:  {name:'landspace',ftable:'fLandspaceTable',ffeas:'fLandspaceFeas',cn:"国土空间规划"}
      },
      formData_Ori: {},
      fileList: [],
      map: null,
      viewNow: null,
      overSource: null,
      overVector: null,
      prj: null,
      prjCode: '4490',
      prjCodeStr: 'EPSG:4490',
      sketch: null,
      measure: null,
      snap: null, //捕捉
      measureTooltipElement: null,
      measureTooltip: null,
      analysisLayerType: '',
      analysisLayer: null,
      analysisLayers: [],
      analysisDraw: null,
      drawFeatures: [],
      attributeTable: {},//用于统计
      attributeTable2: null,//用于分析属性表
      config: {
        regionDatasourceName: null,
        regionDatasetName: null,
        regionFieldName: null,
        featurePicName: '',
        mapCenter: { x: 126, y: 46 },
        'projectLayerTreeData': [
          {
            name: 'historyproject',
            label: '高标准建设历史项目',
            id: '60056a8d-9704-4c56-b259-d0965fc25e77',
            type: 1
          },
          {
            name: 'redline',
            label: '生态红线',
            id: 'c05a8c52-e499-4b1f-9c11-d1bc82807af3',
            type: 1
          },
          {
            name: 'naturalreserve',
            label: '自然保护区',
            id: '9ea32012-9e15-4988-8549-8d750d1183c5',
            type: 1
          },
          {
            name: 'waterprotect',
            label: '水源地保护区',
            id: '7a7e7449-776a-4ba2-a1e6-9cc0328502e8',
            type: 1
          }
          // {
          //   name: 'landspace',
          //   label: '国土空间规划',
          //   id: '64990b7f-1ec2-4f90-8da2-e8ec4114c4e5',
          //   type: 1
          // }
        ]
      },
      x2js: null,
      activeName: 'first',
      project: {
        feature: null
      },
      analysisFeatures: {
        historyproject: undefined,
        redline: undefined,
        naturalreserve: undefined,
        waterprotect: undefined,
        landspace: undefined
        // historypro: undefined
      },
      anaATFeasConfig: {//从FormData读取的属性表展示用的东西
        historyproject: [],
        redline: [],
        naturalreserve: [],
        waterprotect: [],
        landspace: []
        // historypro: []
      },
      analysisTables: {
        historyproject: undefined,
        redline: undefined,
        naturalreserve: undefined,
        waterprotect: undefined,
        landspace: undefined
        // historypro: undefined
      },
      // formData: {
      //
      // },
      rules: {
        fName: [{
          required: true,
          message: '请输入项目名称',
          trigger: 'blur'
        }],
        fNumber: [{
          required: false,
          message: '请输入项目编号',
          trigger: 'blur'
        }],
        fType: [{
          required: true,
          message: '请输入产业类型（种植品种）',
          trigger: 'blur'
        }],
        // fAddress: [{
        //   required: true,
        //   message: '请输入建设地点',
        //   trigger: 'blur'
        // }],
        fContent: [{
          required: true,
          message: '请输入建设内容',
          trigger: 'blur'
        }],
        fScaleArea: [{
          required: true,
          message: '请输入建设规模，单位为万亩',
          trigger: 'blur'
        }],
        fIrrigatePen: [],
        fIrrigateWei: [],
        fIrrigateGuan: [],
        fPlanTotal: [{
          required: true,
          message: '请输入申报总投资',
          trigger: 'blur'
        }],
        fPlanCentral: [],
        fPlanShixian: [],
        fPlanSelf: []
      },
      showBtn: {
        measureLength: true,
        measureArea: true,
        drawPlotting: true,
        localPosition: true,
        rightbtns: 'allClose',
        clearSelected: true
      },
      mcShow: {
        uploadshp:"close",
        loPosition: true,
        drawPlotting: 'allClose',//标绘
        attributeShow: {
          historyproject: false,
          redline: false,
          naturalreserve: false,
          waterprotect: false,
          landspace: false
        },
        showStatics: {
          historyproject: false,
          redline: false,
          naturalreserve: false,
          waterprotect: false,
          landspace: false
        },
        showEmptyResult: {
          historyproject: false,
          redline: false,
          naturalreserve: false,
          waterprotect: false,
          landspace: false
        }
      },
      inshpStyle:new ol.style.Style({
        fill: new ol.style.Fill({
          color: 'rgba(250,250,250,0.0)'
        }),
        stroke: new ol.style.Stroke({
          color: '#00ffff', //'#d74a4a',
          width: 2
        }),
        image: new ol.style.Circle({
          radius: 7,
          fill: new ol.style.Fill({
            color: '#00ffff'
          })
        })
      })

    }
  },
  computed: {
    analyDisabled() {
      if (this.showAdd.tododeal === true) {
        return false//办理的时候可以分析，因此disabled是false
      } else if (this.showAdd.readonly === true) {
        return true
      } else {
        return false
      }
    },
    setVisible: function() {
      return function(arg1) {
        let result = false
        for (let i = 0; i < arg1.length; i++) {
          if (arg1[i] === true) {
            result = true
          }
        }
        return result
      }
    },


  },
  watch: {},
  created() {
    if (this.formData.fId != null) {//不是新增项目。不允许修改所选择的行政区。
      this.formData_Ori = _.cloneDeep(this.formData)//深度拷贝
    }
    Bus.$on('createGBZCBProjectSaveStatisticTable', msg => {
      let that = this
      switch (msg.type) {
        case 'historyproject':
          that.formData.fHistorygbzTable = JSON.stringify(msg.content)//与生态红线相交图形
          break
        case 'redline':
          that.formData.fRedlineTable = JSON.stringify(msg.content)//与生态红线相交图形
          break
        case 'waterprotect':
          that.formData.fWaterprotecTable = JSON.stringify(msg.content)//与生态红线相交图形
          break
        case 'landspace':
          //that.formData.fLandspaceTable = JSON.stringify(msg.content)//与生态红线相交图形
          break
        case 'naturalreserve':
          that.formData.fNaturalreserveTable = JSON.stringify(msg.content)//与生态红线相交图形
          break
      }
    })
    Bus.$on('createGBZCBProjectreReapplySubmit', msg => {
      let that = this
      that.submitForm()
    })
  },
  mounted() {
    //获取当前用户的geom

    this.InitView()
    this.InitMap()
    this.InitMapSource()
    if (this.formData.fId != null) {//新增项目
      this.$nextTick(() => {
        this.initNotCreate()
        this.initNotCreateFeas("fHistorygbzFeas","historyproject")
        this.initNotCreateFeas("fRedlineFeas","redline")
        this.initNotCreateFeas("fWaterprotectFeas","waterprotect")
        this.initNotCreateFeas("fNaturalreserveFeas","naturalreserve")
      })
    }
  },
  methods: {
    openLoadshpPanel(){
      this.mcShow.uploadshp='loadshp';
    },
    //修改或者浏览时的初始化代码。
    initNotCreate() {
      //2.读取项目geometry。
      let format = new ol.format.WKT()
      let featureGbz = format.readFeature(this.formData.geom, {//默认就是4490的坐标
        dataProjection: 'EPSG:4490',
        featureProjection: this.map.getView().getProjection().getCode()
      })
      // feature.getGeometry().getType()可能为GeometryCollection,
      let feas = []
      let geomType = featureGbz.getGeometry().getType().toLowerCase()
      if (geomType === 'geometrycollection') {//好几个面的话就是
        let geos = featureGbz.getGeometry().getGeometries()
        for (let i = 0; i < geos.length; i++) {
          let fea = new ol.Feature({ geometry: geos[i] })
          feas.push(fea)
        }
      } else {
        let geo = featureGbz.getGeometry()
        let fea = new ol.Feature({ geometry: geo })
        feas.push(fea)
      }
      this.project.feature = feas
      this.ZoomToExtent()

    },
    // region 分析事件
    InitAnalysis() {
      let that = this
      axios.all([that.QueryServiceQueryDataAjax(), that.XzqServiceQueryDataAjax()])
        .then(axios.spread(function(queryCatalog, QueryXZQ) {	// spread是将各请求结果拆分返回，如果不使用改方法，则最后的相应结果为一个数组[resp1, resp2]
            //第一个请求
            if (queryCatalog.data.queryData.length > 0) {
              for (var i in queryCatalog.data.queryData) {
                var obj = queryCatalog.data.queryData[i]
                var name = obj.f_name
                var id = obj.f_catalogid
                var dataUrl = obj.f_url //数据服务地址
                var analysisUrl = obj.f_analysisurl //分析服务地址
                var datasourceNames = [{ 'name': obj.f_datasource, 'value': obj.f_datasource }]
                var datasetNames = [{ 'name': obj.f_dataset, 'value': obj.f_dataset }]
                var fieldData = JSON.parse(obj.f_fieldconfig)
                if (analysisUrl != null && analysisUrl != '') {
                  var layerjson = {
                    'name': name,
                    'id': id,
                    'dataUrl': dataUrl,
                    'analysisUrl': analysisUrl,
                    'datasourceName': datasourceNames[0].name,
                    'datasetName': datasetNames[0].name,
                    'fieldData': fieldData
                  }
                  that.analysisLayers.push(layerjson)
                }
              }
            }
            //第二个请求
            if (QueryXZQ.data.queryData.length > 0) {
              var obj = QueryXZQ.data.queryData[0]
              that.dataUrl = obj.f_url
              that.config.regionDatasourceName = obj.datasource
              that.config.regionDatasetName = obj.dataset
              that.config.regionFieldName = obj.field
            }
            that.AnalysisProcess()
          }
          )
        )
    },
    QueryServiceQueryDataAjax() {
      var that = this
      that.analysisLayers = []
      var serviceids = []
      that.map.getLayers().forEach(function(layer, i) {
        if (layer.get('id')) {
          serviceids.push(layer.get('id'))
        }
      })
      let seridsStrTemp = JSON.stringify(serviceids)
      let seridsStr = seridsStrTemp.replace('[', '')
      seridsStr = seridsStr.replace(']', '')
      seridsStr = seridsStr.replace('"', '')
      return getCatalogQueryConfigListByIds({
        "serviceIds": seridsStr.trim()
      });
    },
    XzqServiceQueryDataAjax() {
      return getXzqServerConfigList()
    },

    StartAnalysis(e) {
      let that = this
      if (this.formData.fXzqdm === null || this.formData.fXzqdm.endsWith('00')) {
        that.$message({
          message: '请先选择项目建设地点（所在区县）',
          type: 'error'
        })
        return
      }

      that.analysisLayerType = e.currentTarget.getAttribute('value')
      var queryLayer = that.config.projectLayerTreeData.find((item, index) => {
        return item.name == that.analysisLayerType
      })
      if (queryLayer) {
        that.analysisLayer = globalmf.getLayerById(that.map, queryLayer.id)
        //初始化分析参数
        that.InitAnalysis()
      }
    },
    AnalysisProcess() {
      let that = this
      that.drawFeatures = that.overSource.getFeatures()
      that.loadingtext = '正在检查导入shapefile范围正确性'
      const loading =  this.$loading({
        lock: true,
        customClass: 'create-isLoading',  // *这里设置他的class名称,这里最重要
        text: that.loadingtext,
        spinner: 'el-icon-loading',
        background: 'rgba(83,80,80,0.7)'
      })
      loading.$el.style.fontSize = "50px"
      var analysisGeometries = []
      for (var i in that.drawFeatures) {
        //why20211018转换投影
        var defaultPrjCode = that.globalVar.mmConfig.mapRegion.prjcode
        var mapPrjCode = that.map.getView().getProjection().getCode()
        if (defaultPrjCode != mapPrjCode) {
          that.drawFeatures[i].getGeometry().transform(that.map.getView().getProjection().getCode(),
            that.globalVar.mmConfig.mapRegion.prjcode)
        }
        analysisGeometries.push(that.drawFeatures[i].getGeometry())
      }

      var dataUrl, analysisUrl, datasourceNames, datasetNames, fieldData
      for (var i in that.analysisLayers) {
        var layer = that.analysisLayers[i]
        var name = layer['name']
        var id = layer['id']
        if (that.analysisLayer && that.analysisLayer.get('id') == id) {
          var dataUrl = layer['dataUrl'] //数据服务地址
          var analysisUrl = layer['analysisUrl'] //分析服务地址
          var datasourceName = layer['datasourceName']
          var datasetName = layer['datasetName']
          var fieldData = layer['fieldData']
          //解析分析字段
          var analyseFields = []
          that.config.analysisFields = []
          for (var i in fieldData) {
            var field = fieldData[i]
            var fieldEn = field['f_field']
            var fieldCn = field['f_fieldcn']
            var isvisible = field['f_isvisible']
            var unit = field['f_unit']
            if (isvisible == 1) {
              that.config.analysisFields.push(field)
              analyseFields.push(fieldEn)
            }
          }
          //手绘图形与县界范围做相交
          var sourcedatasetname = that.config.regionDatasetName + '@' + that.config.regionDatasourceName //"XDV700NCFW@smkjk";
          var datasetOverlayAnalystParameters = new SuperMap.DatasetOverlayAnalystParameters({
            sourceDataset: sourcedatasetname,
            operateRegions: analysisGeometries, //[drawFeature.getGeometry()],
            sourceDatasetFields: [that.config.regionFieldName],
            tolerance: 0,
            operation: SuperMap.OverlayOperationType.INTERSECT,
            resultSetting: new SuperMap.DataReturnOption({
              expectCount: 0//不加上这一句，就只返回最多1000条结果
            })
          })
          new ol.supermap.SpatialAnalystService(analysisUrl).overlayAnalysis(datasetOverlayAnalystParameters, function(serviceResult) {
            globalmf.clearSelectedFeature(that.map, that.overSource)
            if (!serviceResult.result) {
              loading.close()
              that.$message({
                message: '输入的图形与行政区界线相交为空！无法进行下一步分析',
                type: 'error'
              })
              return
            }
            var result = serviceResult.result.recordset.features
            var features = (new ol.format.GeoJSON()).readFeatures(result)
            that.overSource.clear()

            //判断当前相交图形是否属于本账号所在范围
            var geometries = []
            for (var i = 0, l = features.length; i < l; i++) {
              var feature = features[i]
              var attributes = feature.getProperties()
              var code = attributes[that.config.regionFieldName]
              //   var userCode = that.globalVar.mmConfig.mapRegion['f_regioncode']
              //var userLevel = that.globalVar.mmConfig.mapRegion['f_levels']
              //  if (code == userCode || code.substr(0, 3) == userCode || userLevel == 1) {
              if (code === that.formData.fXzqdm) {//只能分析指定的区县。
                geometries.push(features[i].getGeometry())
              }
            }
            if (geometries.length > 0) {
              //数据图层与范围图层叠加分析
              var sourcedatasetname = datasetName + '@' + datasourceName
              var datasetOverlayAnalystParameters = new SuperMap.DatasetOverlayAnalystParameters({
                sourceDataset: sourcedatasetname,
                operateRegions: geometries,
                tolerance: 0,
                sourceDatasetFields: analyseFields,
                operation: SuperMap.OverlayOperationType.INTERSECT,
                resultSetting: new SuperMap.DataReturnOption({
                  expectCount: 0//不加上这一句，就只返回最多1000条结果
                })
              })
              that.loadingtext = '正在与专题数据进行叠被分析'
              // alert("正在与专题数据进行叠被分析");
              loading.setText(that.loadingtext)
              new ol.supermap.SpatialAnalystService(analysisUrl).overlayAnalysis(datasetOverlayAnalystParameters, function(serviceResult) {
                globalmf.clearSelectedFeature(that.map, that.overSource)
                if (!serviceResult.result) {
                  that.mcShow.showEmptyResult[that.analysisLayerType] = true
                  let dt = that.divType[that.analysisLayerType]
                  that.formData[dt.ftable] = '{"stainfo":"empty"}'
                  that.formData[dt.ffeas] = '{"stainfo":"empty"}'
                  loading.close()
                  return
                }
                var result = serviceResult.result.recordset.features
                var features = (new ol.format.GeoJSON()).readFeatures(result)
                if (features.length > 0) {
                  that.overSource.clear()
                  //why20211018转换投影
                  var defaultPrjCode = that.globalVar.mmConfig.mapRegion.prjcode
                  var mapPrjCode = that.map.getView().getProjection().getCode()
                  if (defaultPrjCode != mapPrjCode) {
                    that.features[0].getGeometry().transform(that.globalVar.mmConfig.mapRegion.prjcode, that.map.getView().getProjection().getCode())
                    for (var i = 0; i < features.length; i++) {
                      features[i].getGeometry().transform(that.globalVar.mmConfig.mapRegion.prjcode, that.map.getView().getProjection().getCode())
                    }
                  }
                  for (var i = 0; i < features.length; i++) {
                    features[i].setStyle(() => {
                      return new ol.style.Style({
                        fill: new ol.style.Fill({
                          color: 'rgba(100,100,100,0)'
                        }),
                        stroke: new ol.style.Stroke({
                          color: '#62ff00', //'#d74a4a',#ffcc33
                          width: 2
                        })
                      })
                    })
                  }
                  that.overSource.addFeatures(features)
                  //结果显示在属性表里面
                  //var params=[features,that.config.analysisFields,that.map,that.drawFeatures[0],that.analysisLayer.get("id")];
                  that.attributeTable = {
                    features: features,
                    serviceId: that.analysisLayer.get('id'),
                    divType: that.analysisLayerType
                  }
                  let aftObj = { feaResult: result, anaFields: that.config.analysisFields }
                  that.attributeTable2 = [features, that.config.analysisFields, that.map, '', '']
                  that.analysisFeatures[that.analysisLayerType] = JSON.stringify(aftObj)
                  that.mcShow.attributeShow[that.analysisLayerType] = true//属性表界面
                  that.mcShow.showStatics[that.analysisLayerType] = true//统计界面
                  //  let params = [features,  that.config.analysisFields, that.map, '',"" ];
                  that.$nextTick(() => {
                    //   Bus.$emit('intAttributeTable',params);
                  })

                  /*that.mcShow.showStatics=true;*/
                  /* Bus.$emit('setMapBottom',"300px");
                   Bus.$emit('intAttributeTable',params);
                   Bus.$emit('CenterFeature',that.drawFeatures[0]);*/
                  loading.close()
                } else {
                  that.mcShow.showEmptyResult[that.analysisLayerType] = true
                  let dt = that.divType[that.analysisLayerType]
                  that.formData[dt.ftable] = '{"stainfo":"empty"}'
                  that.formData[dt.ffeas] = '{"stainfo":"empty"}'
                  loading.close()
                }

              })

            } else {
              that.$message.error('输入的图形范围超过对应的行政区界线')
              loading.close()
            }
          })

        }

      }
    },
    //endregion
    // region 地图事件
    ZoomToExtent() {
      let that = this
      that.overSource.clear()
      if (that.project.feature) {
        that.overSource.addFeatures(that.project.feature)
        that.ZoomToOverSource()
      } else {
        that.$message({
          message: '请在详细信息中上传项目范围',
          type: 'warning'
        })
      }

    },
    //地图按钮点击事件
    mapBtnIClick(e) {
      let that = this
      let type = e.currentTarget.getAttribute('type')
      switch (type) {
        case 'measureLength'://画线
          that.AddMeasureInteraction('LineString')
          break
        case 'measureArea'://画面
          that.AddMeasureInteraction('Polygon')
          break
        case 'drawPlotting'://标绘
          that.map.removeInteraction(that.measure)
          that.mcShow.drawPlotting = 'drawPlotting'
          break
        case 'clearSelected':
          globalmf.clearLayerByName(that.map, 'xzqRegionLayer') //why20211111
          globalmf.removeAllDrawInteractions(that.map)
          globalmf.removeAllSnapInteractions(that.map)
          globalmf.clearSelectedFeature(that.map, that.overSource)
          break
      }
    },
    /*
    * 添加量测事件
    * @param {type} type
    * @return {undefined}
    */
    AddMeasureInteraction: function(type) {
      let that = this
      that.map.removeInteraction(that.measure)
      that.map.removeInteraction(that.snap)
      that.measure = new ol.interaction.Draw({
        source: that.overSource,
        type: type,
        snapTolerance: 20,
        style: new ol.style.Style({
          fill: new ol.style.Fill({ color: 'rgba(255, 255, 255, 0.2)' }),
          stroke: new ol.style.Stroke({
            color: 'rgba(0, 0, 0, 0.5)',
            lineDash: [10, 10],
            width: 2
          }),
          image: new ol.style.Circle({
            radius: 5,
            stroke: new ol.style.Stroke({ color: 'rgba(0, 0, 0, 0.7)' }),
            fill: new ol.style.Fill({ color: 'rgba(255, 255, 255, 0.2)' })
          })
        })
      })
      that.map.addInteraction(that.measure)
      let snap = new ol.interaction.Snap({
        source: that.overSource
      })
      that.map.addInteraction(snap)
      that.CreateMeasureTooltip()
      let listener
      that.measure.on('drawstart', function(evt) {
        that.sketch = evt.feature
        let tooltipCoord = evt.coordinate
        listener = that.sketch.getGeometry().on('change', function(evt) {
          if (that.sketch != null) {
            let geom = evt.target
            let output
            if (geom instanceof ol.geom.Polygon) {
              output = that.FormatArea(geom)
              tooltipCoord = geom.getInteriorPoint().getCoordinates()
              that.measureTooltipElement.innerHTML = output
              that.measureTooltip.setPosition(tooltipCoord)
            } else if (geom instanceof ol.geom.LineString) {
              output = that.FormatLength(geom)
              tooltipCoord = geom.getLastCoordinate()
              that.measureTooltipElement.innerHTML = output
              that.measureTooltip.setPosition(tooltipCoord)
            }
          }
        })
      }, this)
      that.measure.on('drawend', function() {
        that.measureTooltipElement.className = 'tooltip tooltip-static'
        that.measureTooltip.setOffset([0, -7])
        that.sketch = null
        that.measureTooltipElement = null
        that.CreateMeasureTooltip()
        ol.Observable.unByKey(listener)
      }, this)
    },
    CreateMeasureTooltip: function() {
      let that = this
      if (that.measureTooltipElement) {
        that.measureTooltipElement.parentNode.removeChild(that.measureTooltipElement)
      }
      that.measureTooltipElement = document.createElement('div')
      that.measureTooltipElement.className = 'tooltip tooltip-measure'
      that.measureTooltip = new ol.Overlay({
        id: 'measureResult',
        element: that.measureTooltipElement,
        offset: [0, -15],
        positioning: 'bottom-center'
      })
      that.map.addOverlay(that.measureTooltip)
    },
    //距离测量用到的
    FormatLength: function(line) {
      let that = this
      let output
      let length = ol.sphere.getLength(line, {
        projection: that.map.getView().getProjection().getCode(),
        radius: 6378137
      })
      if (length > 100) {
        output = (Math.round(length / 1000 * 100) / 100) +
          ' ' + 'km'
      } else {
        output = (Math.round(length * 100) / 100) +
          ' ' + 'm'
      }
      return output
    },
    //面积测量用到的
    FormatArea: function(polygon) {
      let that = this
      let area = ol.sphere.getArea(polygon, {
        projection: that.map.getView().getProjection().getCode(),
        radius: 6378137
      })
      let output
      if (area > 10000) {
        output = (Math.round(area / 1000000 * 100) / 100) +
          ' ' + 'km<sup>2</sup>'
      } else {
        output = (Math.round(area * 100) / 100) +
          ' ' + 'm<sup>2</sup>'
      }
      return output
    },
    localPositionClickSpan() {//输入坐标后，点击定位，执行函数
      var lon = parseFloat(this.$refs.lp_coordinateX_text.value)
      var lat = parseFloat(this.$refs.lp_coordinateY_text.value)
      if (lon <= 180 && lon >= -180 && lat <= 90 && lat >= -90) {
        let geom = new ol.geom.Point([lon, lat])
        let feature = new ol.Feature({
          geometry: geom
        })
        this.overSource.addFeature(feature)
        this.map.getView().fit(geom, { maxZoom: 12 })
      } else {
        alert('坐标范围错误')
        return
      }
    },
    localPositionCloseSpan() {
      this.mcShow.loPosition = false
    },
    //endregion
    ZoomToOverSource: function() {
      var that = this
      if (that.overSource == null) {
        return
      }
      if (that.overSource.getFeatures().length == 0) {
        return
      }
      var extent = that.overSource.getExtent()
      //  var extent2 = that.overSource.getExtent()
      let extent2 = [extent[0] - 0.2, extent[1] - 0.2, extent[2] + 0.2, extent[3] + 0.2]
      var extentObj = {
        center: { x: (extent[0] + extent[2]) / 2, y: (extent[1] + extent[3]) / 2 },
        width: Math.abs(extent[2] - extent[0]),
        height: Math.abs(extent[3] - extent[1])
      }
      var tol = that.tol
      if (extentObj.width < tol && extentObj.height < tol) {
        extent = [extentObj.center.x - tol / 2, extentObj.center.y - tol / 2, extentObj.center.x + tol / 2, extentObj.center.y + tol / 2]
      }
      let viewold = that.map.getView()
      viewold.fit(extent2, { size: that.map.getSize(), padding: [20, 20, 20, 20] })
      setTimeout(function() {
        let viewnew = new ol.View({
          projection: ol.proj.get('EPSG:4490'), //ol.proj.get("EPSG:4326"),
          resolutions: viewold.getResolutions(),
          center: [extentObj.center.x, extentObj.center.y],
          // maxZoom: 18,
          // minZoom: 8,
          extent: extent2
          // Zoom: 8
          // constrainResolution: true,
          // smoothResolutionConstraint: true,
        })

        that.map.setView(viewnew)
        //  extent = that.overSource.getExtent()
        //globalmf.zoomToExtent(that.map, extent)
        that.map.getView().setZoom(8)
        //   that.map.getView().setZoom(9);
        //  viewnew.fit(extent, { size: that.map.getSize(), padding: [20, 20, 20, 20] })
      }, 500)

      //
      // view.setMaxZoom(18);
      // view.setMinZoom(10);

    },
    ChangeMenuCss(e) {
      let that = this
      let type = e.currentTarget.getAttribute('type')
      if (this.showBtn.rightbtns === type) {
        this.showBtn.rightbtns = 'allClose'
      } else {
        this.showBtn.rightbtns = type
      }
    },
    // 文件上传成功时的函数
    fileChange(file) {
      let that = this
      this.fileList = []
      this.overSource.clear()
      this.project.feature = null
      let existFile = this.fileList.slice(0, this.fileList.length - 1).find(f => f.name === file.name)//如果文件名重复
      if (existFile) {
        this.$message.error('当前文件已经存在!')
        this.fileList.pop()
      } else {
        this.fileList.push(file)
      }

      let uploadUrl = gConfig.spbtdir.defaulturl + gConfig.spbturl.portal.upload.uploadShpfile
      //let uploadUrl = "http://192.168.3.187:8085/portal/upload/upload.shpfile";
      let fd = new FormData()
      //fd.append("name", this.name);
      that.fileList.forEach(item => {
        //文件信息中raw才是真的文件
        fd.append('files', item.raw)
        //console.log(item.raw)
      })
      const loading = Loading.service({
        lock: true,
        customClass: 'create-isLoading',  // *这里设置他的class名称,这里最重要
        text: '正在上传shapefile文件，若文件过大，则需要花费一定时间，请耐心等待',
        spinner: 'el-icon-loading',
        background: 'rgba(83,80,80,0.7)'
      })
      uploadShpFileZip(fd).then(res => {
        if (res.code === 200) {
          if (res.data.status === "error") {
            this.$message.error(res.data.msg)
          } else if (res.data.status === 400) {
            this.$message.error("上传shp文件有错误，请检查文件是否正确。  " + res.data.message)
          }
          let props = res.data.queryData.data.props
          let features = []
          let format = new ol.format.WKT()
          let geojsonFormat = new ol.format.GeoJSON()
          let sumArea=0;
          //先计算一遍面积
          for (let index in props) {
            let prop = props[index]
            let geowkt = prop.the_geom//这是wkt格式的

            let featuresSum = format.readFeature(geowkt, {
              dataProjection: 'EPSG:' + res.data.epsgId,
              featureProjection:'EPSG:4530'
            })
            let farea = ol.sphere.getArea(featuresSum.getGeometry());
            sumArea+=farea;
          }
          //266666680对应40万亩
          if(sumArea>266666680){
            loading.close();
            this.$message.error('上传文件面积过大，请减少图斑后重新上传')
            return;
          }

          for (let index in props) {
            let prop = props[index]
            let geowkt = prop.the_geom//这是wkt格式的
            let feature = format.readFeature(geowkt, {
              dataProjection: 'EPSG:' + res.data.epsgId,
              featureProjection: that.map.getView().getProjection().getCode()
            })
            feature.set('featureid', 'inputshp')
            feature.setStyle(that.inshpStyle)
            features.push(feature)
          }

          // let featuresGeojson = geojsonFormat.writeFeatures(features)
          // var param = {
          //   'geojson': featuresGeojson,
          //   'operatetype': 'temp',
          //   'name': res.data.fileName
          // }
          that.overSource.addFeatures(features)
          that.project.feature = features
          that.formData.geom = format.writeFeatures(that.project.feature)
          that.ZoomToOverSource()
          loading.close()
          this.$message.success('上传成功')
          this.mcShow.uploadshp = 'close'
        } else {
          this.$message.error('失败')
        }
      }).catch((error) => {
        // catch 指请求出错的处理
        console.log(error)
      })
    },
    handleFilUploadSuccess(res, file, fileList) {
      console.log(res, file, fileList)

    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    TabClick(tab) {
      let that = this
      that.Next(tab.index - 0 + 1)
    },
    Next(index) {
      let that = this
      switch (index) {
        case 1:
          that.activeName = 'first'
          break
        case 2:
          that.activeName = 'second'
          break
        case 3:
          that.ZoomToExtent()
          that.activeName = 'third'
          if (that.project.feature) {
         //   that.openData('historyproject')
          }
          break
        case 4:
          //打开生态红线数据
          that.ZoomToExtent()
          that.activeName = 'fourth'
          if (that.project.feature) {
            that.openData('redline')
          }
          break
        case 5://自然保护区
          that.ZoomToExtent()
          that.activeName = 'fifth'
          if (that.project.feature) {
            that.openData('naturalreserve')
          }
          break
        case 6://水源地保护
          that.ZoomToExtent()
          that.activeName = 'sixth'
          if (that.project.feature) {
            that.openData('waterprotect')
          }
          break
        case 7://国土空间规划
          that.ZoomToExtent()
          // that.openData('landspace')
          that.activeName = 'seventh'
          break
      }
    },
    openData(value) {
      let that = this
      var queryLayer = that.config.projectLayerTreeData.find((item, index) => {
        return item.name == value
      })
      if (queryLayer) {
        that.map.getLayers().forEach(function(layer, i) {
          if (layer.get('id') != queryLayer.id) {
            if (that.config.projectLayerTreeData.find((item, index) => {
              return item.id == layer.get('id')
            })) {
              layer.setVisible(false)
            }
          } else {
            layer.setVisible(that.layerVisable)//高标准农田正常不可以查看
          }
        })
        //2022年9月1日 LQ 加上掩膜maskgeom之后非常怪，会出现掩膜extent大片空白挡住了地图，所以先去掉
        //但是在一张图里没有这个问题。先搁置这个问题吧
         let emParam = { id: queryLayer.id, open: true ,maskgeom:that.formData.geom}
       // let emParam = { id: queryLayer.id, open: true }
        Bus.$emit('getNodeDataInLeftCatalog', emParam)
      }
    },
    regionChange(data) {
      console.log(data)
    },
    feaReProject(features) {
      let that = this
      if (features.length > 0) {
        //why20211018转换投影
        let defaultPrjCode = that.globalVar.mmConfig.mapRegion.prjcode
        let mapPrjCode = that.map.getView().getProjection().getCode()
        if (defaultPrjCode != mapPrjCode) {
          that.fresult[0].getGeometry().transform(that.globalVar.mmConfig.mapRegion.prjcode, that.map.getView().getProjection().getCode())
          for (let i = 0; i < features.length; i++) {
            features[i].getGeometry().transform(that.globalVar.mmConfig.mapRegion.prjcode, that.map.getView().getProjection().getCode())
          }
        }
      }
      return features
    },

    //不是新增项目。不允许修改所选择的行政区。
    initNotCreate2() {

      if (!this.formData_Ori.fHistorygbzFeas) {
        this.anaATFeasConfig.historyproject = []
        return
      }
      let fs = JSON.parse(this.formData_Ori.fHistorygbzFeas)
      if (fs.hasOwnProperty('stainfo')) {//表示空
        this.anaATFeasConfig.historyproject = []
      } else if (fs.hasOwnProperty('feaResult')) {
        let fresult = fs.feaResult
        let features = (new ol.format.GeoJSON()).readFeatures(fresult)
        features = this.feaReProject(features)
        let tc = [features, fs.anaFields, this.map, '', '']
        this.anaATFeasConfig.historyproject = tc
      } else {
        this.anaATFeasConfig.historyproject = []
      }
    },
    initNotCreateFeas(feas,atfc) {
      if (!this.formData_Ori[feas]) {
        this.anaATFeasConfig[atfc] = []
        return
      }
      let fs = JSON.parse(this.formData_Ori[feas])
      if (fs.hasOwnProperty('stainfo')) {//表示空
        this.anaATFeasConfig[atfc] = []
      } else if (fs.hasOwnProperty('feaResult')) {
        let fresult = fs.feaResult
        let features = (new ol.format.GeoJSON()).readFeatures(fresult)
        features = this.feaReProject(features)
        let tc = [features, fs.anaFields, this.map, '', '']
        this.anaATFeasConfig[atfc] = tc
      } else {
        this.anaATFeasConfig[atfc] = []
      }
    },
    //region 地图初始化
    InitLayers() {
      let that = this
      let option = {
        url: 'http://192.168.3.187:8090/iserver/services/map-agscache-BIGHLJImageXH/wmts100',
        name: '黑龙江影像底图',
        id: 'c0b2c2e4-dc0e-4a5d-9efb-af88387eeec2',
        sys: 'EPSG:4490',
        zIndex: 9999,
        type: 'image',
        zmin: 1,
        zmax: 11
      }
      //let Layer = that.addWMTS4490Layer(that.map, option, null)
    },
    InitMapSource() {
      let that = this
      that.overSource = new ol.source.Vector({ crossOrigin: 'anonymous', wrapX: false })
      that.overVector = new ol.layer.Vector({
        source: that.overSource,
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(100,100,100,0.2)'
          }),
          stroke: new ol.style.Stroke({
            color: '#005aff', //'#d74a4a',#ffcc33
            width: 2
          }),
          image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill({
              color: '#005aff'
            })
          })
        })
      })
      that.map.addLayer(that.overVector)
      that.overVector.setZIndex(9999)
      if(that.globalVar.mmConfig.mapRegion.geomwkt){
      let format = new ol.format.WKT()
      let featureXJ = format.readFeature(that.globalVar.mmConfig.mapRegion.geomwkt, {//默认就是4490的坐标
        dataProjection: 'EPSG:4490',
        featureProjection: this.map.getView().getProjection().getCode()
      })
        featureXJ.setStyle(() => {
          return new ol.style.Style({
            fill: new ol.style.Fill({
              color: 'rgba(100,100,100,0)'
            }),
            stroke: new ol.style.Stroke({
              color: '#fe2525', //'#d74a4a',#ffcc33
              width: 3
            })
          })
        })
        that.overSource.addFeature(featureXJ);
      }
    },
    InitMap() {
      var that = this
      that.map = new ol.Map({
        target: 'proMap',
        controls: ol.control.defaults({
          attributionOptions: ({
            collapsible: false//2022年2月28日 LQ 很诡异，map的一堆control初始都有问题。
          })
        }).extend([
          new ol.control.MousePosition({//2022年2月28日 LQ，这两个Control位置有问题，等到有空的时候看看
            coordinateFormat: ol.coordinate.createStringXY(4),
            className: 'custom-mouse-position',
            target: document.getElementById('mouse-position'),
            undefinedHTML: '&nbsp;'
          }),
          new ol.control.ScaleLine()//2022年2月28日 LQ，这两个Control位置有问题，等到有空的时候看看
        ]),
        view: that.viewNow
      })
      that.mapSourceLoad=true;
    },
    InitView() {
      var that = this
      //2021年10月15日 LQ  3857的view
      var resolutions3857 = []
      var matrixIds3857 = new Array(22)
      for (var z = 0; z < 22; ++z) {
        resolutions3857[z] = 156543.033928041 / Math.pow(2, z)
        matrixIds3857[z] = z
      }
      var envelope3857 = {}
      envelope3857.left = -20037508.3427892
      envelope3857.bottom = -20037508.3427892
      envelope3857.right = 20037508.3427892
      envelope3857.top = 20037508.3427892
      that.prj3857 = ol.proj.get('EPSG:3857')
      that.prj3857.setExtent([envelope3857.left, envelope3857.bottom, envelope3857.right, envelope3857.top])
      that.prj3857.setWorldExtent([envelope3857.left, envelope3857.bottom, envelope3857.right, envelope3857.top])
      that.view3857 = new ol.View({
        projection: that.prj3857,
        resolutions: resolutions3857,
        center: [14357455, 5806768],
        zoom: 9
      })
      that.view3857.setMinZoom(9) //最小放大到9级，8级的话 平面坐标显示就有问题了
      //2021年10月15日 LQ  4490的view
      var topResolution = 360.0 / 512
      var resolutions = []
      for (var zoom = 0; zoom < 22; zoom++) {
        resolutions.push(topResolution / Math.pow(2, zoom))
      }
      proj4.defs('EPSG:4490', '+proj=longlat +ellps=GRS80 +no_defs')
      that.prj = ol.proj.get(that.prjCodeStr)
      var envelope = {}
      envelope.left = -180
      envelope.bottom = -90
      envelope.right = 180
      envelope.top = 90
      that.prj.setExtent([envelope.left, envelope.bottom, envelope.right, envelope.top])
      that.prj.setWorldExtent([envelope.left, envelope.bottom, envelope.right, envelope.top])
      let extent = [that.globalVar.mmConfig.mapRegion.f_xmin-0.2, that.globalVar.mmConfig.mapRegion.f_ymin-0.2, that.globalVar.mmConfig.mapRegion.f_xmax + 0.2, that.globalVar.mmConfig.mapRegion.f_ymax + 0.2]
      var extentObj = {
        center: { x: (extent[0] + extent[2]) / 2, y: (extent[1] + extent[3]) / 2 },
        width: Math.abs(extent[2] - extent[0]),
        height: Math.abs(extent[3] - extent[1])
      }
      that.view4490 = new ol.View({
        projection: that.prj, //ol.proj.get("EPSG:4326"),
        resolutions: resolutions,
        center: [(extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2 ],
        extent: extent,
        zoom: 6
      })
      //按照用户选择投影坐标系
      that.viewNow = that.view4490
      /*if (that.globalVar.mmConfig.mapRegion.userPrjCode == "EPSG:3857") {
    that.viewNow = that.view3857;
    that.mapTemplate.proj = '3857';//绑定了投影对应的radio。
  } else {
    that.viewNow = that.view4490;
    that.mapTemplate.proj = '4490';
  }*/
    },
    //endregion
    submitForm() {
      let that = this
      //1.填写项目状态
      that.formData.fState = 0//建设状态 0代表存在 2代表删除,1表示通过审批，正式成为储备项目
      //2.填写formData上传shp的几何信息和分析矢量图形,在上传shp时已经赋值了geom
      // that.formData.geom = (that.project.feature == undefined) ? null : new ol.format.WKT().writeFeatures(that.project.feature)
      // if(that.formData.fHistorygbzFeas===null)
      that.formData.fHistorygbzFeas = (that.analysisFeatures.historyproject == undefined) ? that.formData.fHistorygbzFeas : that.analysisFeatures.historyproject
      // if(that.formData.fRedlineFeas===null)
      // that.formData.fRedlineFeas = (that.analysisFeatures.redline == undefined) ? that.formData.fRedlineFeas : new ol.format.WKT().writeFeatures(that.analysisFeatures.redline)
      that.formData.fRedlineFeas = (that.analysisFeatures.redline == undefined) ? that.formData.fRedlineFeas : that.analysisFeatures.redline
      //  if(that.formData.fWaterprotectFeas===null)
      that.formData.fWaterprotectFeas = (that.analysisFeatures.waterprotect == undefined) ? that.formData.fWaterprotectFeas : that.analysisFeatures.waterprotect
      // if(that.formData.fNaturalreserveFeas===null)
      that.formData.fNaturalreserveFeas = (that.analysisFeatures.naturalreserve == undefined) ? that.formData.fNaturalreserveFeas : that.analysisFeatures.naturalreserve
      // if(that.formData.fLandspaceFeas===null)
      //  that.formData.fLandspaceFeas = (that.analysisFeatures.landspace == undefined) ? that.formData.fLandspaceFeas : new ol.format.WKT().writeFeatures(that.analysisFeatures.landspace)
      //3.行政区判断

      if (this.formData.fXzqdm === null) {
        that.$message({
          message: '必须填写项目所在区县!',
          type: 'error'
        })
        return
      }
      //4.各类项目分析后的统计表查看，有null的表示没有分析，不允许。直接return，
      for (let i in this.formData) {
        if (i.endsWith('Table')) {
          if (this.formData[i] === null) {
            that.$message({
              message: '有叠被数据没有被分析，请先进行分析!',
              type: 'error'
            })
            return
          }
        }
      }
      //5.验证表单必填项是否填写
      that.$refs['elForm'].validate(valid => {
        // TODO 提交表单
        if (valid) {
          if (that.formData.fId === null) {//没有id表示是新增的
            addGbzcb(that.formData).then(response => {
              that.msgSuccess('新增成功')
              that.open = false
              that.showAdd.showcp = false
              // that.getList()
            })
          } else {//有id表示表示有项目，是修改或者查看
            that.formData.updateTime = null
            that.formData.createTime = null
            updateGbzcb(that.formData).then(response => {
              that.msgSuccess('修改成功')
              that.open = false
              that.showAdd.showcp = false
              // that.getList()
            })
          }

        } else {
          that.$message({
            message: '有必填项没有被填写，请检查!',
            type: 'error'
          })
        }
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    },
    closeThisCom() {
      let that = this
      if (that.showAdd.readonly === true) {
        that.showAdd.showcp = false
      } else {
        this.$confirm('是否关闭项目储备页面？ 关闭后所有已填写的信息都不会保留！', '警告', {
          confirmButtonText: '确定关闭',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          that.showAdd.showcp = false
          that.showAdd.showcp = false
        })
      }
    },
    //上传shp的回调函数
    handleLoadFeatoMap(feas){
      this.overSource.addFeatures(feas)
      this.project.feature = feas
      let format = new ol.format.WKT()
      this.formData.geom = format.writeFeatures(this.project.feature)
      this.ZoomToOverSource()
    },
  },
  beforeDestroy() {
    Bus.$off('createGBZCBProjectSaveStatisticTable')
    Bus.$off('createGBZCBProjectreReapplySubmit')

  }

}
</script>
<style scoped>
/*令el-tabs可以有overflow*/
::v-deep .el-tabs--card {
  height: calc(100vh - 80px);
  /* overflow-y: auto; */
}
::v-deep  .el-tab-pane {
  height: calc(100vh - 80px);
  overflow-y: auto;
}
.xjxzq-input{
  float: left;
  width: auto;
}

.ri-bot{
  position: absolute;
  right: 0;
  width: 40%;
  height: 150px;
  bottom: 0px;
  background-color: #eafdeb;
}
.next-last{
  margin:  10px 0px 70px 0px;
}
/*::v-deep .el-loading-spinner .el-loading-text{*/
/*  color: #19d1d4;*/
/*  font-size: 50px;*/
/*}*/


/*::v-deep .el-loading-spinner i {*/
/*  color: #19d1d4;*/
/*  font-size: 50px;*/
/*}*/
/*::v-deep .el-upload-dragger {*/
/*  width: 300px;*/
/*  height: 140px;*/
/*}*/

::v-deep .el-upload-dragger .el-icon-upload {
  font-size: 50px;
  line-height: 10px;
}


.el-form-item {
  text-align: center;
}

.el-form-item__content {
  margin-left: 0px !important;
}

.addressDetail {
  margin-top: 10px;
}

.mouse-position {
  position: absolute;
  bottom: 45px;
}

.projectForm {
  position: absolute;
  /*top: 15px;*/
  left: 0;
  width: 58%;
  height: 100%;
  /*overflow-y: auto;*/
}

/*#proMap {*/
/*  position: absolute;*/
/*  !*top: 15px;*!*/
/*  right: 0;*/
/*  width: 40%;*/
/*  height: 100%;*/
/*}*/
.right-panel {
  position: absolute;
  /*top: 15px;*/
  right: 0;
  width: 40%;
  height: 100%;
}

/*地图操作*/
.layer-switch {
  right: 8px;
  bottom: 40px;
  display: block;
  background-color: rgba(255, 255, 255, .5) !important;
  padding: 3px 3px 0px 3px;
  height: 30px;
  /* margin-bottom: 13px; */
  font-size: 16px;
  position: absolute;
  z-index: 1;
  border-radius: 4px;
  box-shadow: #000 0px 0px 5px;
}

.ol-scale-line {
  bottom: 25px !important;
}

.map-btns {
  position: absolute;
  z-index: 1;
  right: 8px;
  bottom: 170px;
  display: block;
  padding: 3px 3px 0px 3px;
  background-color: rgba(255, 255, 255, .5);
  border-radius: 4px;
}

.closeCP {
  position: absolute;
  z-index: 1;
  right: 8px;
  /*top: 10px;*/
  display: block;
  /*padding: 3px 3px 0px 3px;*/
  /*color: rgba(255, 249, 249);*/
  /*border-radius: 4px;*/
  /*background-color: #2fcba8;*/
  /*border-color: #ccc;*/
  /*height: 30px;*/
  /*width: 40px;*/
}

.map-btn {
  height: 30px;
  margin-bottom: 13px;
  font-size: 16px;
  line-height: 1.5;
}

.map-btns i {
  color: #ffffffeb;
  cursor: pointer;
  width: 25px;
  height: 25px;
  border-radius: 4px;
  display: inline;
  padding: 4px;
  background-color: #008680;
  border-color: #ccc;
}

.map-btn .sub-menu {
  right: 31px;
  display: flex;
  background-color: rgba(255, 255, 255, .5);
  position: absolute;
  margin-top: -25px;
  height: 46px;
  box-shadow: #000 0px 0px 5px;
  border-radius: 4px;
  padding: 4px;
}

.map-btn label {
  display: block;
  color: #000000;
  font-weight: normal;
  font-size: 6px;
  text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
}

.sub-menu .map-btn {
  margin: 0px 2px;
}

.localPosition-popup {
  margin-left: -266px;
  margin-top: -50px;
  background-color: rgba(255, 255, 255, .5);
  width: 250px;
  height: 110px;
  padding: 10px;
  box-sizing: border-box;
  text-align: center;
  line-height: 33px;
}

.localPosition-popup span[type=position] {
  background-color: #008680;
  color: #fff;
  border-radius: 5px;
  padding: 2px 10px;
  line-height: 20px;
  cursor: pointer;
  margin: 0 10px 0 10px;
}

.catalog-div {
  width: auto !important;
  height: auto !important;
  /* bottom: 160px;*/
  padding-bottom: 12px;
  margin-left: 34px;
  border-radius: 5px;
  max-width: 300px;
  /*min-width: 200px;*/
  position: absolute;
  overflow: auto;
  z-index: 100;
  top: 12px;
  background-color: #004a47ab;
}

.savebtn {
  /*background-color: #00afff;*/
  /*padding: 10px 20px;*/
  /*font-size: 14px;*/
  /*border-radius: 4px;*/
  margin-left: 50px !important;
}

.emptyinfo {
  font-size: 20px;
  margin: 50px 0px 50px 0;
  background-color: #c8ddfb;
  /*margin: 0px 0px 0px -80px;*/
}
.emptyinfo2 {
  font-size: 20px;
  margin: 0px 0px 10px 0;
  background-color: #c8fbcb;
  /*margin: 0px 0px 0px -80px;*/
}

.seeinfo {
  font-size: 20px;
  margin: 20px 0px 0px 0px;
  background-color: #d9ffe7;
}

.cbstform {
  margin: 0px 0px 0px -80px;
}
</style>
<style scoped lang="scss">
.create-isLoading {
  .el-loading-spinner {
    //top: 50%;
    //left: 50%;
    //margin-left: -55px;
    background: rgba(127, 126, 126, 0.7);
    //padding: 20px;
    //border-radius: 4px;
    //width: auto;
    //text-align: center;
    //position: absolute;

    i {
      color: #1c25de;
      font-size: 50px;
    }

    .el-loading-text {
      color: #1c25de;
      //color: #31e635;
      font-size: 30px;
    }
  }
}
</style>
